<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="container">
      <!-- 上半部分 -->
      <div class="top-section">
        <Button
          class="btn"
          icon="md-arrow-forward"
          type="primary"
          @click="handleChartClick"
          >温度曲线</Button
        >
      </div>

      <!-- 下半部分 -->
      <div class="bottom-section">
        <vxe-table
          :data="tableData"
          border
          stripe
          class="table"
          show-overflow
          :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
        >
          <vxe-column field="name" title="参数名称"></vxe-column>
          <vxe-column
            field="setUpperLimit.value"
            title="设定上限℃"
            :edit-render="{}"
          >
            <template #edit="{ row}">
              <vxe-input
                v-model="row.setUpperLimit.value"
                type="number"
                min="0"
                max="999"
                @blur="handleCellBlur(row, 'setUpperLimit')"
              ></vxe-input>
            </template>
          </vxe-column>
          <vxe-column
            field="setLowerLimit.value"
            title="设定下限℃"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <vxe-input
                v-model="row.setLowerLimit.value"
                type="number"
                min="0"
                max="999"
                @blur="handleCellBlur(row, 'setLowerLimit')"
              ></vxe-input>
            </template>
          </vxe-column>
          <vxe-column
            field="tempAdjust.value"
            title="温度修正℃"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <vxe-input
                v-model="row.tempAdjust.value"
                type="number"
                min="0"
                max="999"
                @blur="handleCellBlur(row, 'tempAdjust')"
              ></vxe-input>
            </template>
          </vxe-column>
          <vxe-column
            field="actualTemp.value"
            title="实际温度℃"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <vxe-input
                v-model="row.actualTemp.value"
                type="number"
                min="0"
                max="100"
                @blur="handleCellBlur(row, 'actualTemp')"
              ></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="autoSwitch.value" title="自动开关">
            <template #default="{ row }">
              <i-switch
                size="large"
                v-model="row.autoSwitch.value"
                @on-change="handleAutoSwitchChange(row, 'autoSwitch')"
              >
                <template #open>
                  <span>自动</span>
                </template>
                <template #close>
                  <span>手动</span>
                </template>
              </i-switch>
            </template>
          </vxe-column>
          <vxe-column field="heatingStatus.value" title="加热状态">
            <template #default="{ row }">
              <Button
                :disabled="row.autoSwitch.value"
                :type="row.heatingStatus.value ? 'success' : 'error'"
                @click="handleStatusChange(row, 'heatingStatus')"
              >
                {{ row.heatingStatus.value ? '运行中' : '停止中' }}
              </Button>
            </template>
          </vxe-column>
          <vxe-column field="coolingStatus.value" title="冷却状态">
            <template #default="{ row }">
              <Button
                :disabled="row.autoSwitch.value"
                v-if="showCooling(row)"
                :type="row.coolingStatus.value ? 'success' : 'error'"
                @click="handleStatusChange(row, 'coolingStatus')"
              >
                {{ row.coolingStatus.value ? '运行中' : '停止中' }}
              </Button>
            </template>
          </vxe-column>
          <vxe-column
            field="valveOpening.value"
            title="加热流量阀开合度(%)"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <vxe-input
                v-if="showCooling(row)"
                v-model="row.valveOpening.value"
                type="number"
                min="0"
                max="100"
                @blur="handleCellBlur(row, 'valveOpening')"
              ></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="overTempAlarm.value" title="报警状态">
            <template #default="{ row }">
              <div
                class="status"
                :class="{ 'status-error': row.overTempAlarm.value }"
              >
                {{ row.overTempAlarm.value ? '超温报警' : '' }}
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  N_TempMonitor,
  tableData
} from './config';

@T_srv.comp
export default class cTempMonitor extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.inject({ default: () => {} }) addTabFunc;

  /* 组件名 */
  private name: string = 'cTempMonitor';

  private funName: string = 'cTempMonitor';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  private isMask: boolean = false;

  private tableData: N_TempMonitor.TableData[] = tableData();

  private hasAlert = false;

  private alertMessage = '';

  private timer: number | null = null;

  public ecDetCodes: string[] = [];

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
    this.loadData();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_command.startTask();
    this.receiveEvent();
  }

  private receiveEvent() {
    this.$bus.$on(
      '__PLC_CONNSTATE__',
      (data: { connState: boolean; ecBoxName: string }) => {
        if (data.ecBoxName === 'mianyang') {
          if (data.connState) {
            if (!this.GT_command.isOpenTask) {
              this.GT_command.startTask();
            }
          } else {
            this.GT_command.stopTask();
          }
        }
      }
    );
  }

  private init() {
    this.ecDetCodes = [];
    this.tableData.forEach(row => {
      Object.keys(row).forEach(key => {
        if (key !== 'name') {
          this.ecDetCodes.push(row[key].code);
        }
      });
    });
  }

  public updateData(res: ifs.I_scadaReadResp['data']) {
    this.tableData.forEach(row => {
      Object.keys(row).forEach(key => {
        if (key !== 'name' && key !== '_XID') {
          const value =
            row[key].conversionRate === 1
              ? res[row[key].code].v
              : res[row[key].code].v / row[key].conversionRate;
          row[key].value = value;
        }
      });
    });
  }

  destroyed() {
    this.GT_command.stopTask();
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    this.$bus.$off('__PLC_CONNSTATE__');

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private loadData() {
    // 初始化表格数据
    Tsrv.readPlcData(this.ecDetCodes).then(res => {
      if (typeof res !== 'boolean') {
        this.updateData(res);
      }
    });
  }

  private handleChartClick() {
    this.$store
      .dispatch('getLayoutConfigAsync', {
        funid: null,
        field: 'cHistoricalCurve',
        type: 'custom'
      })
      .then((res: any) => {
        if (res) {
          this.addTabFunc('cHistoricalCurve');
        }
      });
  }

  private handleCellBlur(
    row: N_TempMonitor.TableData,
    field: keyof N_TempMonitor.TableData
  ) {
    if (field === 'name') return;
    // const newValue = row[field].value;
    // const oldValue = row[field].value; // 初始值与新值相同

    const v =
      row[field].conversionRate === 1
        ? row[field].value.toString()
        : ((row[field].value as number) * row[field].conversionRate).toString();
    const d = [{ ecDetCode: row[field].code, value: v }];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this.tableData.forEach(item => {
            if (item.name === row.name) {
              item[field].value =
                row[field].conversionRate === 1
                  ? res[row[field].code].v
                  : res[row[field].code].v / row[field].conversionRate;
            }
          });
        }
      });
    });
  }

  private showCooling(row: N_TempMonitor.TableData): boolean {
    return ['硫酸阳极化11槽', '硫酸阳极化12槽', '铬酸阳极化15槽'].includes(
      row.name
    );
  }

  private handleAutoSwitchChange(
    row: N_TempMonitor.TableData,
    field: keyof N_TempMonitor.TableData
  ) {
    if (field === 'name') return;
    const d = [
      { ecDetCode: row[field].code, value: row[field].value.toString() }
    ];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this.tableData.forEach(item => {
            if (item.name === row.name) {
              item[field].value = res[row[field].code].v;
            }
          });
        }
      });
    });
  }

  private handleStatusChange(
    row: N_TempMonitor.TableData,
    field: keyof N_TempMonitor.TableData
  ) {
    if (field === 'name') return;
    const val = !row[field].value;
    const data = [{ ecDetCode: row[field].code, value: val.toString() }];
    Tsrv.writePlcData(data).then(_ => {
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          row[field].value = res[row[field].code].v;
        }
      });
    });
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: column;

  .top-section {
    display: flex;
    justify-content: end;
  }

  .bottom-section {
    height: 90%;
    padding: 20px;
    .table {
      height: 90%;
    }
  }

  @keyframes pulse-alert {
    0%,
    100% {
      transform: scale(1);
      background-color: #fff1f0;
    }
    50% {
      transform: scale(1.05);
      background-color: #ffccc7;
    }
  }

  .status {
    width: 100%;
    height: 100%;
    text-align: center;
  }

  .status-error {
    color: #510f11;
    background-color: #e72b1e;
    border: 1px solid #b90f06;
    border-radius: 4px;
    animation: pulse-alert 1s infinite;
  }
}
</style>
